package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.domain.Question;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserLocationApi userLocationApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }

    //查询推荐列表
    public PageResult recommendation(Integer page, Integer pageSize) {
        Long toUserId = UserHolder.getUserId();
        List<RecommendUser> list = recommendUserApi.findRecommendUserList(toUserId, page, pageSize);
        if (CollUtil.isEmpty(list)) {
            list = defaultList();
        }
        //将RecommendUser转换成TodayBest对象
        List<TodayBest> todayBestList = new ArrayList<>();
        for (RecommendUser recommendUser : list) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
            todayBestList.add(todayBest);
        }
        return new PageResult(page, pageSize, 0l, todayBestList);
    }

    //今日佳人
    public TodayBest todayBest() {
        //1. 获取用户id
        Long toUserId = UserHolder.getUserId();
        //2. 使用Api获取当前用户缘分值最大的用户信息
        RecommendUser recommendUser = recommendUserApi.findWithMaxScore(toUserId);
        //3. 如没有，就添加假数据---针对的新用户
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(90d);
            recommendUser.setUserId(1L);
        }
        //4. 获取出推荐用户的信息
        Long id = recommendUser.getUserId();
        UserInfo userInfo = userInfoApi.findById(id);
        //4. 将RecommedUser对象转换成TodayBest对象
        return TodayBest.init(userInfo, recommendUser);
    }

    //根据用户id获取佳人信息
    public TodayBest personalInfo(Long userId) {
        //1. 根据userId获取信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2. 获取当前用户id（获取缘分值）
        Long friendId = UserHolder.getUserId();
        RecommendUser user = recommendUserApi.queryByUserId(userId, friendId);
        //3. 构造返回的vo对象
        TodayBest vo = TodayBest.init(userInfo, user);
        return vo;

    }

    //根据用户id查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java吗？" : question.getTxt();
    }

    //回复问题
    public void reply(Long userId, String reply) {
        //1. 创建map集合，保存问题
        Map map = new HashMap();
        map.put("userId", UserHolder.getUserId());
        map.put("huanXinId", "hx" + UserHolder.getUserId());
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        //2. 发布消息的json字符串
        String message = JSON.toJSONString(map);
        //3. 发布消息
        huanXinTemplate.sendMsg("hx" + userId, message);
    }

    //搜索附近
    public List<NearUserVo> search(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //1. 根据userId和distance查找附近用户id的集合
        List<Long> userIds = userLocationApi.searchNear(userId, distance);
        //2. 查询附近人的用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3. 遍历封装
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : userIds) {
            //3.1 排除自己
            if (id == userId){
                continue;
            }
            UserInfo userInfo = map.get(id);
            //3.2 性别筛选
            if (!gender.equals(userInfo.getGender())){
                continue;
            }
            //3.3 封装
            NearUserVo vo = NearUserVo.init(userInfo);
            vos.add(vo);
        }
        return vos;
    }
}
